#include <iostream>
#include <signal.h>
#include "http/server.h"
#include "asset/manager.h"

// 全局服务器实例指针，用于信号处理
HttpServer *server = nullptr;

// 信号处理函数，用于优雅关闭服务器
void handleSignal(int signal)
{
    if (server)
    {
        std::cout << "\nReceived signal to stop server. Shutting down..." << std::endl;
        server->stop();
    }
    exit(0);
}

int main(int argc, char *argv[])
{
    try
    {
        // 初始化资产管理器
        AssetManager assetManager;

        // 加载已保存的资产数据
        if (!assetManager.loadFromFile("assets.dat"))
        {
            std::cout << "No existing assets found. Starting with empty inventory." << std::endl;
        }
        else
        {
            std::cout << "Loaded " << assetManager.getAssetCount() << " assets from storage." << std::endl;
        }

        // 创建并配置HTTP服务器
        server = new HttpServer(8080, &assetManager);

        // 设置信号处理
        signal(SIGINT, handleSignal);
        signal(SIGTERM, handleSignal);

        std::cout << "Asset Management Server started on port 8080" << std::endl;
        std::cout << "Available endpoints:" << std::endl;
        std::cout << "  GET    /assets         - List all assets" << std::endl;
        std::cout << "  GET    /assets/{id}    - Get asset by ID" << std::endl;
        std::cout << "  POST   /assets         - Create new asset (JSON body)" << std::endl;
        std::cout << "  PUT    /assets/{id}    - Update asset (JSON body)" << std::endl;
        std::cout << "  DELETE /assets/{id}    - Delete asset" << std::endl;
        std::cout << "Press Ctrl+C to stop server" << std::endl;

        // 启动服务器
        server->start();

        // 服务器停止后保存资产数据
        assetManager.saveToFile("assets.dat");
        std::cout << "Assets saved to storage." << std::endl;

        getchar(); // 等待用户输入，防止程序立即退出
        delete server;
        return 0;
    }
    catch (const std::exception &e)
    {
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;
    }
}
